<?php

namespace app\api\controller;

use app\common\controller\Api;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\model\ddns\Access;
use app\common\model\ddns\Domain;
use app\common\model\ddns\Log;
use think\db\exception\DataNotFoundException;

/**
 * 首页接口
 */
class Ddns extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $accessModel = null;
    protected $domainModel = null;
    protected $logModel = null;

    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->accessModel = new Access();
        $this->domainModel = new Domain();
        $this->logModel = new Log();
    }

    /**
     * 首页
     *
     */
    public function index()
    {
        //需解析的域名信息
        $domain = $this->domainModel
            ->where('id', 1)
            ->find();

        $ip = $this->getMyAddress();
        //查询到的ip不是最后一次解析的ip则进行重新解析对应二级域名ip
        if ($domain['last_ip'] != $ip) {
            $this->changeDdns($ip, $domain);
        }
        //保存解析ip
        $domainSaveData = [
            'last_ip' => $ip
        ];
        $this->domainModel
            ->where('id', 1)
            ->update($domainSaveData);
        $logSavaData = [
            'domain' => $domain['domain_name'] . '.' . $domain['main_domain'],
            'ip' => $ip,
            'create_time' => time(),
        ];
        $this->logModel
            ->insert($logSavaData);
        return;

    }

    /**
     * 得到自己的IP地址
     *
     */
    public function getMyAddress()
    {
        $domain = $this->domainModel
            ->where('id', 1)
            ->find();
        $szUrl = $domain['access_ip'];
        $UserAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $szUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);  //0表示不输出Header，1表示输出
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_ENCODING, '');
        curl_setopt($curl, CURLOPT_USERAGENT, $UserAgent);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        $data = curl_exec($curl);
        $data=mb_convert_encoding($data,'UTF-8','UTF-8,GBK,GB2312,BIG5');
        $preg = '/(\d{1,3}\.){3}\d{1,3}/';
        preg_match($preg, $data, $matches);
        $myIpAddress=$matches[0];
        return $myIpAddress;

    }

    public function changeDdns($newIp, $domain)
    {
        //阿里账号的key
        $access = $this->accessModel
            ->where('id', 1)
            ->find();
        AlibabaCloud::accessKeyClient($access['access_key_id'], $access['access_key_secret'])
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Alidns')
                // ->scheme('https') // https | http
                ->version('2015-01-09')
                ->action('UpdateDomainRecord')
                ->method('POST')
                ->host('alidns.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'RecordId' => $domain['record_id'],
                        'RR' => $domain['domain_name'],
                        'Type' => "A",
                        'Value' => $newIp,
                    ],
                ])
                ->request();
            print_r($result->toArray());
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }
}
